const express = require('express');
const { body, query, param } = require('express-validator');
const orderController = require('../controllers/orderController');
const { authenticate, authorize } = require('../middleware/auth');
const { validate } = require('../middleware/validation');

const router = express.Router();

// 创建订单验证规则
const createOrderValidation = [
    body('shippingAddress')
        .isObject()
        .withMessage('必须提供收货地址'),
    body('shippingAddress.firstName')
        .notEmpty()
        .withMessage('收货人姓氏不能为空'),
    body('shippingAddress.lastName')
        .notEmpty()
        .withMessage('收货人名字不能为空'),
    body('shippingAddress.address')
        .notEmpty()
        .withMessage('详细地址不能为空'),
    body('shippingAddress.city')
        .notEmpty()
        .withMessage('城市不能为空'),
    body('shippingAddress.postalCode')
        .notEmpty()
        .withMessage('邮政编码不能为空'),
    body('shippingAddress.phone')
        .notEmpty()
        .withMessage('联系电话不能为空'),
    body('paymentMethod')
        .isIn(['credit_card', 'paypal', 'bank_transfer', 'cash_on_delivery'])
        .withMessage('请选择有效的支付方式')
];

// 支付验证规则
const paymentValidation = [
    body('paymentMethod')
        .isIn(['credit_card', 'paypal', 'bank_transfer'])
        .withMessage('请选择有效的支付方式')
];

// 管理员更新订单状态验证规则
const updateStatusValidation = [
    body('status')
        .isIn(['pending', 'paid', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'])
        .withMessage('请选择有效的订单状态'),
    body('trackingNumber')
        .optional()
        .isLength({ max: 100 })
        .withMessage('快递单号不能超过100个字符')
];

// 查询验证规则
const queryValidation = [
    query('page')
        .optional()
        .isInt({ min: 1 })
        .withMessage('页码必须为正整数'),
    query('limit')
        .optional()
        .isInt({ min: 1, max: 100 })
        .withMessage('每页数量必须在1-100之间'),
    query('status')
        .optional()
        .isIn(['pending', 'paid', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'])
        .withMessage('请选择有效的订单状态')
];

// 用户路由
router.post('/', authenticate, createOrderValidation, validate, orderController.createOrder);
router.get('/', authenticate, queryValidation, validate, orderController.getUserOrders);
router.get('/:id', authenticate, orderController.getOrder);
router.put('/:id/cancel', authenticate, orderController.cancelOrder);
router.post('/:id/payment', authenticate, paymentValidation, validate, orderController.processPayment);

// 管理员路由
router.get('/admin/all', authenticate, authorize('admin'), queryValidation, validate, orderController.getAllOrders);
router.put('/admin/:id/status', authenticate, authorize('admin'), updateStatusValidation, validate, orderController.updateOrderStatus);

module.exports = router;